local M = {}
M.window = {}

local options = {
	relative = "cursor",
	style = "minimal",
	row = 1,
	col = 1,
	border = "single",
	filetype = "markdown", -- 可以配置文件类型, 语法高亮显示
	zindex = 50,
}

-- 获取字符串列表中最长字符串的长度
local max_width_in_lines = function(lines)
	local max_width = vim.api.nvim_strwidth(lines[1])
	for i = 2, #lines do
		local v = vim.api.nvim_strwidth(lines[i])
		if v > max_width then
			max_width = v
		end
	end
	return max_width
end

M.open_window = function()
	local lines = { "# hello world", "this is a floating window!", "- this is line three", "- this is line four" }

	local width = max_width_in_lines(lines)
	local height = #lines -- lines的函数做为高度

	-- 创建buf容纳lines字符串列表
	local buf = vim.api.nvim_create_buf(false, true)
	vim.api.nvim_buf_set_lines(buf, 0, -1, true, lines)
	vim.api.nvim_set_option_value("filetype", options.filetype, { buf = buf })

	-- 打开一个新的浮动窗口
	local win = vim.api.nvim_open_win(buf, false, {
		relative = options.relative,
		style = options.style,
		width = width,
		height = height,
		row = options.row,
		col = options.col,
		border = options.border,
		zindex = options.zindex,
	})
	if M.window._current then
		vim.api.nvim_win_close(M.window._current.win, false)
		vim.api.nvim_buf_delete(M.window._current.buf, {})
		M.window._current = nil
	end
	M.window._current = { win = win, buf = buf }
end

-- 当光标移动后, 关闭窗口
vim.api.nvim_create_autocmd("CursorMoved", {
	callback = function()
		if M.window._current then
			vim.api.nvim_win_close(M.window._current.win, false)
			vim.api.nvim_buf_delete(M.window._current.buf, {})
			M.window._current = nil
		end
	end,
	once = false, -- 回调函数是否只会执行一次 
})

return M

-- How to test:
-- :lua require('hello.floating').open_window()
